###
the BaseObject is like Object in Java the base class for all tree classes

it defines these methods:
    disconnet(callback)
    emit(name, args)
    connect(name, callback)
###

clone_object = (obj) ->
    c = do () ->
    c.prototype = obj;

    return new c

class tree.BaseObject

    constructor: ->
        @eventmap = {}

    connect: (name, callback, args) ->
    
        if not @eventmap[name]?
            @eventmap[name] = [[callback, args]]
        
        else
            @eventmap[name].push [callback, args]
            
    disconnect: (callback) ->
        tmp = @eventmap;
        @eventmap = {};
    
        for field, part of tmp
            do (field, part) ->
                for item in part
                    do (item) ->
                        func = item[0]
                        if func != callback
                            @eventmap[field] = callback


    emit: (name, event) ->
        parts = @eventmap[name]
        if not parts
            return
        for part in parts
            callback = part[0]
            args = part[1]
            if callback
                callback @, event, args
    
    clone: () ->
        return clone_object @
    

tree.using = (name) ->
    ###
    Copy the namespace into the global namespace. Be careful, this can pollute the global namespace and objects
    might be overridden.
    ###
    `var parts = name.split('.');
    var before = window;
    for(var i=0; i<parts.length; i++)
    {
        var part = parts[i];
        if(before[part] == null || before[part].prototype == null)
            if(before[part] == null)
            {
                throw new TypeError("namespace " + part + " doesnt exist");
            }
            else
            {
                before = before[part];
            }
        else
        {
            throw new TypeError(part + " is a class");
        }
        for(field in before)
        {
            window[field] = before[field];
        }
    }`
    return null

